var curTarget = null;
function createElement(text) {
  var element = document.createElement("textarea");
  //设置元素只读
  element.setAttribute("readonly", "");
  element.value = text;
  document.body.appendChild(element);
  return element;
}
// 监听来自 background.js sendContentScan 的消息
var getXPathForElement = (element) => {
  const allNodes = document.getElementsByTagName("*");
  for (
    let segs = [];
    element && element.nodeType === 1;
    element = element.parentNode
  ) {
    if (element.hasAttribute("id")) {
      let uniqueIdCount = 0;
      for (let n = 0; n < allNodes.length; n++) {
        if (allNodes[n].hasAttribute("id") && allNodes[n].id === element.id)
          uniqueIdCount++;
        if (uniqueIdCount > 1) break;
      }
      if (uniqueIdCount === 1) {
        segs.unshift(`id("${element.getAttribute("id")}")`);
        return segs.join("/");
      } else {
        segs.unshift(
          `${element.localName.toLowerCase()}[@id="${element.getAttribute(
            "id"
          )}"]`
        );
      }
    } else {
      let xPathIndex = 1;
      for (
        let sibling = element.previousSibling;
        sibling;
        sibling = sibling.previousSibling
      ) {
        if (sibling.nodeType === 1 && sibling.localName === element.localName)
          xPathIndex++;
      }
      const tagName = element.localName.toLowerCase();
      const nthChild = `[${xPathIndex}]`;
      segs.unshift(`${tagName}${nthChild}`);
    }
  }
  return segs.length ? `/${segs.join("/")}` : null;
};
chrome.runtime.onMessage.addListener(async function (
  request,
  sender,
  sendResponse
) {
  if (request.action === "sendContentScan") {
    let { text } = request.data;
    // 调用桌面通知
    var element = createElement(text);
    element.select();
    element.setSelectionRange(0, element.value.length);
    document.execCommand("copy");
    element.remove();
    sendResponse(`识别成功:${text},已复制到剪贴板`);
    return true;
  }
  if (request.action == "selectNode") {
    let { curForm, key } = request.data;
    console.log(request.data,'request.data;');
  }
  if (request.action == "getXPath") {
    console.log(request, "request");
  }
});
